package com.jp.knowledge.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.WeChatModel;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.PaySelectView;
import com.jp.knowledge.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.xutils.common.util.MD5;
import org.xutils.view.annotation.ViewInject;

/**
 * Created by 528787067@qq.com on 2017/3/2.
 */

public class PayActivity extends SlidingActivity implements View.OnClickListener, ResultSubscriber.OnResultListener {

    public static final String WECHAT_PAY_SUCCESS = "wechatPaySuccess";
    public static final String WECHAT_PAY_ERR_CODE = "wechatPayErrCode";
    public static final String WECHAT_PAY_SCOOP_ID = "wechatPayScoopId";
    public static final String WECHAT_PAY_USER_ID = "wechatPayUserId";
    public static final String WECHAT_PAY_TYPE = "wechatPayType";
    public static final String WECHAT_PAY_USER_NAME = "wechatPayUserName";
    public static final String WECHAT_PAY_USER_ICON = "wechatPayUserIcon";

    public static void gotoPay(Context context, String scoopId, String userId, int toType, String userName, String userIcon){
        context.startActivity(new Intent(context, PayActivity.class)
                .putExtra("scoopId", scoopId).putExtra("userId", userId).putExtra("toType", toType)
                .putExtra("userName", userName).putExtra("userIcon", userIcon));
    }

    @ViewInject(R.id.pay_head_icon)
    private ImageView userHeadIv;
    @ViewInject(R.id.pay_user_name)
    private TextView userNameTv;
    @ViewInject(R.id.pay_money_select)
    private PaySelectView moneySelector;
    @ViewInject(R.id.pay_wechat_select_cb)
    private CheckBox wechatSelectCb;
    @ViewInject(R.id.pay_commit_pay)
    private TextView commitPayBtn;

    private IWXAPI api;
    private String scoopId;
    private String userId;
    private int toType;
    private String userName;
    private String userIcon;

    private BroadcastReceiver weChatBroadcaseReciver;
    private LocalBroadcastManager weChatLocalBroadcastManager;

    @Override
    protected int getResourceId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void init() {
        initTitle();
        initWeChatBroadcastReceiver();
        Intent intent = getIntent();
        scoopId = intent.getStringExtra("scoopId");
        userId = intent.getStringExtra("userId");
        toType = intent.getIntExtra("toType", 16);
        userName = intent.getStringExtra("userName");
        userIcon = intent.getStringExtra("userIcon");
        if(userIcon != null && userIcon.trim().length() > 0)
            ImageLoadUtil.loadCircle(this, userIcon, userHeadIv);
        if(userName != null && userName.trim().length() > 0)
            userNameTv.setText(userName);
        else
            userNameTv.setVisibility(View.GONE);
        commitPayBtn.setOnClickListener(this);
        initIWXAPI();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        weChatLocalBroadcastManager.unregisterReceiver(weChatBroadcaseReciver);
    }

    @Override
    public void finish() {
        moneySelector.hideKeyboard();
        super.finish();
    }

    private void initTitle(){
        rightBtn.setText("历史");
        topName.setText("打赏");
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        leftIcon.setVisibility(View.VISIBLE);
        rightBtn.setVisibility(View.VISIBLE);
        topDesc.setVisibility(View.GONE);
        rightIcon.setVisibility(View.GONE);
        leftIcon.setOnClickListener(this);
        rightBtn.setOnClickListener(this);
    }

    private void initIWXAPI(){
        api = WXAPIFactory.createWXAPI(this, "wx73bea73b9ead58e8", true);
        api.registerApp("wx73bea73b9ead58e8");
    }

    private void initWeChatBroadcastReceiver(){
        weChatLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        weChatBroadcaseReciver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getAction() != WXPayEntryActivity.WECHAT_PAY)
                    return;
                int errCode = intent.getIntExtra(WXPayEntryActivity.WECHAT_PAY_ERR_CODE, -1);
                switch (errCode){
                    case BaseResp.ErrCode.ERR_OK:           // 支付成功
                        weChatLocalBroadcastManager.sendBroadcast(new Intent(WECHAT_PAY_SUCCESS)
                            .putExtra(WECHAT_PAY_ERR_CODE, errCode)
                            .putExtra(WECHAT_PAY_SCOOP_ID, scoopId)
                            .putExtra(WECHAT_PAY_USER_ID, userId)
                            .putExtra(WECHAT_PAY_TYPE, toType)
                            .putExtra(WECHAT_PAY_USER_NAME, userName)
                            .putExtra(WECHAT_PAY_USER_ICON, userIcon));
                        finish();
                        break;
                    case BaseResp.ErrCode.ERR_USER_CANCEL:  // 支持取消
                        break;
                    case BaseResp.ErrCode.ERR_COMM:         // 支持失败
                        break;
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WXPayEntryActivity.WECHAT_PAY);
        weChatLocalBroadcastManager.registerReceiver(weChatBroadcaseReciver, intentFilter);
    }

    /**
     * | token | string |  |  | 是 | 用户识别码 |
     | toId | string |  |  | 是 | 对应ID   |
     | toType | int |  |  | 是 |  对应类型 |
     | payType | int |  |  | 是 | 支付类型   |
     | payMethod | string |  |  | 是 | 支付方式WECHATPAY微信支付  JPPAY竞品说钱包支付   |
     | toUserId | string |  |  | 是 | 打赏给某用户的id   |
     | body | string |  |  | 是 | 商品描述   |
     | detail | string |  |  | 否 | 商品详情   |
     | attach | string |  |  | 否 | 商品附加参数 原样返回   |
     | trade_type | string |  |  | 是 |交易类型   |
     | device_info | string |  |  | 否 |设备信息  |
     | total_fee | int |  |  | 是 | 金额单位为分  |
     | notify_url | String |  |  | 否 |回调通知地址 |
     | order_type | int |  |
     */
    private void startPay(){
        JsonObject param = new JsonObject();
        param.addProperty("total_fee", moneySelector.getSelectMoney());    // 金额
        param.addProperty("toId", scoopId);                              // 团队圈 Id
        param.addProperty("toUserId", userId);                              // 打赏用户 Id
        param.addProperty("body", "团队圈打赏");                            // 描述
        param.addProperty("trade_type", "APP");                             // 交易类型
//        param.addProperty("spbill_create_ip", NetUtil.getIPAddress(this)); // 客户端IP
        param.addProperty("toType", toType);                                // 支付对象类型（接口文档）
        param.addProperty("payType", 1001);                                     // 支付类型( 1提现 2赞赏 3会员充值 4商城支付)
        param.addProperty("payMethod", "WECHATPAY");                       // 支付方法（WECHATPAY-微信支付  JPPAY-竞品说钱包支付）
        HttpHelper.getInstance(this).wechatPay(param, 0x01, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                finish();
                break;
            case R.id.right_bn:
                break;
            case R.id.pay_commit_pay:
                if(!wechatSelectCb.isChecked())
                    ToasUtil.toast(this, "请选择支付方式");
                else if(scoopId == null || scoopId.trim().length() == 0
                        || userId == null || userId.trim().length() == 0)
                    ToasUtil.toast(this, "抱歉，打赏信息有误");
                else if(moneySelector.getSelectMoney() < 0)
                    ToasUtil.toast(this, "请选择合理的打赏金额");
                else if(moneySelector.getSelectMoney() < 0.01)
                    ToasUtil.toast(this, "打赏金额最小为0.01元");
                else
                    startPay();
                break;
        }
    }

    @Override
    public void onStart(int requestType) {
        loading.show();
    }
    @Override
    public void onCompleted(int requestType) {
        loading.cancel();
    }
    @Override
    public void onError(int requestType) {
        ToasUtil.toast(this, "抱歉，打赏失败，请稍后重试");
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
            return;
        }
        WeChatModel weChatModel = data.getEntity(WeChatModel.class);
        PayReq req = new PayReq();
        req.appId = weChatModel.getAppid();
        req.nonceStr = weChatModel.getNonce_str();
        req.packageValue = "Sign=WXPay";
        req.partnerId = weChatModel.getMch_id();
        req.prepayId = weChatModel.getPrepay_id();
        req.timeStamp = System.currentTimeMillis()/1000+"";
        String sign = "appid=" + req.appId
                + "&noncestr=" + req.nonceStr
                + "&package=" + req.packageValue
                + "&partnerid=" + req.partnerId
                + "&prepayid=" + req.prepayId
                + "&timestamp=" + req.timeStamp
                + "&key=" + "a97fb5d166240fbe0e8270aa344835f8";
        req.sign = MD5.md5(sign).toUpperCase();
        api.sendReq(req);
    }
}
